package priv.zgh.forum.auth.controller;


import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import priv.zgh.forum.annotation.CheckToken;
import priv.zgh.forum.auth.entity.User;
import priv.zgh.forum.auth.entity.ZhengGu;
import priv.zgh.forum.auth.service.UserService;
import priv.zgh.forum.auth.vo.ResultLoginVo;
import priv.zgh.forum.auth.vo.UserInfoVo;
import priv.zgh.forum.exception.ForumException;
import priv.zgh.forum.utils.CaptchaUtils;
import priv.zgh.forum.utils.JwtUtils;
import priv.zgh.forum.utils.R;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ZGH
 * @since 2021-10-22
 */
@CrossOrigin
@RestController
@RequestMapping("/auth/user")
public class UserController {

    // 存储的验证码
    ZhengGu saveCode = new ZhengGu();

    @Resource
    private DefaultKaptcha captchaProducer;

    // 登录验证码SessionKey(Session名称)
    public static final String LOGIN_VALIDATE_CODE = "login_validate_code";

    private UserService userService;
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    public R login(@RequestBody User user){
        if(user == null){
            throw new ForumException(20001,"并没有传入参数!");
        }
        String userId = userService.login(user);
        if(userId != null && !userId.equals("")){
            User userInfo = userService.getById(userId);
            String token = JwtUtils.createJWT(6000000, userInfo);
            ResultLoginVo resultLoginVo = new ResultLoginVo();
            resultLoginVo.setToken(token);
            resultLoginVo.setUserId(userId);
            return R.ok().data("data",resultLoginVo);
        }else{
            throw new ForumException(20001,"账号或者用户名错误!");
        }
    }

    @ApiOperation("管理员登录")
    @PostMapping("/admin-login")
    public R adminLogin(@RequestBody User user){
        return R.ok().data("token","admin");
    }

    @ApiOperation("管理员信息")
    @GetMapping("/admin-info")
    public R adminInfo(){
        return R.ok().data("roles","[admin]").data("name","admin").data("avatar","https://c-ssl.duitang.com/uploads/item/202105/02/20210502011942_ypncr.jpg");
    }

    @ApiOperation("获取登录验证码图片")
    @GetMapping(value = {"/loginValidateCode/{random}"})
    public void loginValidateCode(HttpServletRequest request, HttpServletResponse response,@PathVariable("random") Integer random) throws Exception{
        CaptchaUtils.validateCode(request,response,captchaProducer,LOGIN_VALIDATE_CODE,saveCode);
//        System.out.println("保存在服务端的验证码:" + saveCode);
    }

    @ApiOperation("检查验证码是否正确")
    @PostMapping("/checkLoginValidateCode")
    public R checkLoginValidateCode(HttpServletRequest request,@RequestBody HashMap<String,Object> map) {
        String code = (String)map.get("code");
//        整蛊?读取不到
//        String loginValidateCode = request.getSession().getAttribute(LOGIN_VALIDATE_CODE).toString();
        HashMap<String,Object> result = new HashMap<>();
        if(code == null || code.equals("")){
            result.put("message","验证码未填!");//验证码为空
        }
        else if(saveCode.getTemp() == null || saveCode.getTemp().equals("")){
            return R.ok().data("status",false);//验证码过期
        }else if(saveCode.getTemp().equals(code)){
            return R.ok().data("status",true);//验证码正确
        }else if(!saveCode.getTemp().equals(code)){
            return R.ok().data("status",false);//验证码不正确
        }
        return R.ok().data("message","未知错误");
    }

    @ApiOperation("注册")
    @PostMapping("/register")
    public R register(@RequestBody User user){
        System.out.println(user);
        if(user == null){
            throw new ForumException(20001,"注册数据错误!");
        }
        int count = userService.register(user);
        if(count > 0){
            return R.ok().message("注册成功!");
        }else {
            return R.error().message("注册失败!");
        }
    }

    @CheckToken
    @GetMapping("/getMessage")
    public R getMessage(){
        return R.ok().message("访问成功!");
    }

    @ApiOperation("根据Token信息获取用户基本信息")
    @PostMapping("/getUserInfoByToken")
    public R getUserInfoByToken(HttpServletRequest request) {
        // 从 http 请求头中取出 token
        String token = request.getHeader("token");
        // 执行认证
        if (token == null || token.isEmpty()) {
            throw new ForumException(20001, "无token，请重新登录");
        }
        // 获取 token 中的 user id
        String userId;
        try {
            userId = JWT.decode(token).getClaim("id").asString();
        } catch (JWTDecodeException j) {
            throw new ForumException(20001, "访问异常！");
        }
        // 从数据库中取出数据然后进行数据传递
        User user = userService.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setId(user.getId());
        userInfoVo.setUsername(user.getUsername());
        userInfoVo.setEmail(user.getEmail());
        userInfoVo.setNickname(user.getNickname());
        return R.ok().data("userInfo", userInfoVo);
    }
}

